 //
//  CityCommunityListViewController.m
//  cityStar
//
//  Created by joyban on 15-2-4.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "CityCommunityListViewController.h"
#import "merchantListCell.h"
#import "HWSearchViewController.h"

#import "StayViewController.h"
#import "RepairAndHomeViewController.h"
#import "CommunityDetailViewController.h"
//#import "FSDropDownMenu.h"
#import "SingleTableView.h"
#import "UIColor+FlatUI.h"

#import "SVPullToRefresh.h"
#import "supplierlibsModel.h"

#import "UserCityModel.h"
#import "HTDefine.h"

NSString *const CityListTableViewCellID = @"CityListTableViewCellID";

@interface CityCommunityListViewController ()<SingleTableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *merchantListTable;
@property (weak, nonatomic) IBOutlet UIButton *AllBusinessdistrictbtn;
@property (weak, nonatomic) IBOutlet UIButton *AlltypeBtn;
@property (weak, nonatomic) IBOutlet UIButton *Intelligencebtn;

@property(nonatomic,strong) NSMutableArray *cityArr;
@property(nonatomic,strong) NSMutableArray *cityNameArray;
@property(nonatomic,strong) NSMutableArray *idArray;

@property (nonatomic,weak) IBOutlet UIImageView *addressImageView;
@property (strong, nonatomic) SingleTableView *SelectCityTableView;

//@property (nonatomic, strong) FSDropDownMenu *menu;
@property (nonatomic, assign) BOOL isShowAddressList;
@property (nonatomic, weak) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *typeImageView;
@property (strong, nonatomic) SingleTableView *typeSingleTableView;
@property (nonatomic, weak) IBOutlet UIImageView *noopsycheImageView;
@property (strong, nonatomic) SingleTableView *noopsycheSingleTableView;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *arrayRequest;
@property (nonatomic, strong) NSString *merchantID;

@property (nonatomic, strong) NSString *strOrder;
@property (nonatomic, strong) NSString *strPrice;
@property (nonatomic, strong) NSString *strDistrict;

@end

@implementation CityCommunityListViewController

-(id)initWithMerchartID:(NSString *)merchantID
{
    self = [super init];
    if (self) {
        self.merchantID = merchantID;
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @[@"全部分类",@"便利店",@"社区行政",@"社区医疗",@"生活服务",@"生鲜水果",@"餐饮旅社",@"便民维修",@"家政服务"][(NSInteger)self.type];
    self.arrayRequest = [[NSMutableArray alloc]init];
    [self addBackButton];
    [self setUpTableViews];
    __weak typeof(self)weakSelf = self;
    [self addRightButtonWithImage:[UIImage imageNamed:@"bsearch" ] actionBlock:^{
        HWSearchViewController *hwSearchViewController = [[HWSearchViewController alloc]init];
        hwSearchViewController.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:hwSearchViewController animated:YES];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAddressStatues) name:@"isShowAddressList" object:nil];
    
    self.cityArr = [[NSMutableArray alloc]init];
    self.cityNameArray = [[NSMutableArray alloc]init];
    self.idArray = [[NSMutableArray alloc]init];
    self.strOrder = @"";
    self.strDistrict = @"";
    self.strPrice = @"";

//    self.areaArr = @[
//                     @[@"附近",@"500米",@"1000米",@"2000米",@"5000米"],
//                     @[@"徐家汇",@"人民广场",@"陆家嘴"],
//                     @[@"三里屯",@"亚运村",@"朝阳公园"],
//                     @[@"同城"],
//                     ];
//    self.currentAreaArr = _areaArr[0];
//    FSDropDownMenu *menu = [[FSDropDownMenu alloc] initWithOrigin:CGPointMake(0, 36) andHeight:300];
//    menu.transformView = self.addressImageView;
//    menu.tag = 1001;
//    menu.dataSource = self;
//    menu.delegate = self;
//    [self.view addSubview:menu];
    
    NSString *celltest =  @[@"全部分类",@"便利店",@"社区行政",@"社区医疗",@"生活服务",@"生鲜水果",@"餐饮旅社",@"便民维修",@"家政服务"][(NSInteger)self.type];
    if (celltest.length >= 5) {
        NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
        ;
        [self.AlltypeBtn setTitle:btnTitle forState:UIControlStateNormal];
    }else{
        [self.AlltypeBtn setTitle:celltest forState:UIControlStateNormal];
    }
    
    
    [self.merchantListTable addPullToRefreshWithActionHandler:^{
        self.page = 1;
        [weakSelf webRequest_GetCityCommunityWithMore:NO];

    }];
    [self.merchantListTable addInfiniteScrollingWithActionHandler:^{
        [weakSelf webRequest_GetCityCommunityWithMore:YES];

    }];
    [self.merchantListTable triggerPullToRefresh];
    
    [self webRequest_GetMyUserCity];
}

- (void)webRequest_GetMyUserCity
{
    [HttpRequestManager getMethod:KinterFace_MyUserCity parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        NSLog(@"%@",response);
        if (success) {
            [self.cityArr addObjectsFromArray:response[@"value"][@"content"]];
//            NSMutableArray *array = [[NSMutableArray alloc]init];
//            for (NSDictionary *model in self.cityArr) {
//                [array addObject:model[@"name"]];
//            }
            [self.cityNameArray addObject:@"全部社区"];
            [self.cityArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                [self.cityNameArray addObject:obj[@"name"]];
            }];
            [self.idArray addObject:@""];
            [self.cityArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                [self.idArray addObject:obj[@"id"]];
            }];
        }
    }];
}

- (void)webRequest_GetCityCommunityWithMore:(BOOL)isMore
{
    if (self.merchantID) {
        NSString *postUrl = [NSString stringWithFormat:@"%@/brand/%@/page/%i/city/%@",KInterface_GetSupplierQuery,self.merchantID,isMore?self.page:0,[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122"];
        [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                DLog(@"%@",response);
                if (isMore) {
                    [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                    self.page = self.page + 1;
                }else{
                    self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
                }
                [self.merchantListTable reloadData];
            }
            if (isMore) {
                [self.merchantListTable.infiniteScrollingView stopAnimating];
            }else{
                [self.merchantListTable.pullToRefreshView stopAnimating];
            }
        }];
    }else{
        NSString *EndUrl = @"";
        //    self.ylongitude = 30.315992;
        //    self.xlatitude = 120.134352;
        if(![self.strOrder isEqualToString:@""])
        {
            self.type = [self.strOrder floatValue];
        }
        
        if(![self.strDistrict isEqualToString:@""])
        {
            int n = 0;
            for (int i = 0; i<self.idArray.count; i++) {
                if([self.strDistrict isEqualToString:[NSString stringWithFormat:@"%@",self.idArray[i]]])
                {
                    n = i - 1;
                    break;
                }
            }
            self.ylongitude = [self.cityArr[n][@"latitude"] floatValue]/10000000;
            self.xlatitude = [self.cityArr[n][@"longtitude"] floatValue]/10000000;
        }else{
            self.ylongitude = 0;
            self.xlatitude = 0;
        }
        
        NSString *postUrl = [NSString stringWithFormat:@"%@/type/%li/y/%f/x/%f/page/%i",KInterface_CityShopList,(long)self.type,self.xlatitude,self.ylongitude,isMore?self.page:0];
        EndUrl = postUrl;

        if(![self.strPrice isEqualToString:@""])
        {
            EndUrl = [NSString stringWithFormat:@"%@/sort/1",EndUrl];
        }
        [HttpRequestManager getMethod:[EndUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                DLog(@"%@",response);
                if (isMore) {
                    [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                    self.page = self.page + 1;
                }else{
                    self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
                }
                [self.merchantListTable reloadData];
            }
            if (isMore) {
                [self.merchantListTable.infiniteScrollingView stopAnimating];
            }else{
                [self.merchantListTable.pullToRefreshView stopAnimating];
            }
        }];
    }
}

- (void)addRightButtonWithImage:(UIImage *)image actionBlock:(void(^)(void))block
{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setFrame:CGRectMake(0, 0, 20, 20)];
    [rightButton setImage:image forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightBar_Touched:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:@"bsearch_touch"] forState:UIControlStateHighlighted];
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.rightBarActionBlock = block;
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}

-(void)changeAddressStatues
{
    self.isShowAddressList = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUpTableViews
{
    [self.merchantListTable registerNib:[merchantListCell nib] forCellReuseIdentifier:CityListTableViewCellID];
}
#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [merchantListCell heightOfTableCell];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayRequest.count;
}

#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    merchantListCell *MerchantListCell = [tableView dequeueReusableCellWithIdentifier:CityListTableViewCellID];
    supplierlibsModel *merchat = [supplierlibsModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    [MerchantListCell setDataWithModeli:merchat];
    MerchantListCell.selectionStyle = UITableViewCellSelectionStyleGray;
    return MerchantListCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
    NSString *strid = [NSString stringWithFormat:@"%@",self.arrayRequest[indexPath.row][@"id"]];
//    supplierlibsModel *merchat = [supplierlibsModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    RepairAndHomeViewController *repairAndHomeViewController = [[RepairAndHomeViewController alloc]initWithMerchantID:strid];
    [self.navigationController pushViewController:repairAndHomeViewController animated:YES];
}

#pragma mark - Actions
-(IBAction)allTypes_atction:(id)sender
{
   
    if(self.AlltypeBtn.selected == NO)
    {
        self.AlltypeBtn.selected = YES;
    }else
    {
        self.AlltypeBtn.selected = NO;
    }
    self.AllBusinessdistrictbtn.selected = NO;
    self.Intelligencebtn.selected = NO;
    
    [self.typeSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.typeSingleTableView.dataArray = @[@"全部分类",@"便利店",@"社区行政",@"社区医疗",@"生活服务",@"生鲜水果",@"餐饮旅社",@"便民维修",@"家政服务"];
}

-(IBAction)Intelligence_atction:(id)sender
{
    if(self.Intelligencebtn.selected == NO)
    {
        self.Intelligencebtn.selected = YES;
    }else
    {
        self.Intelligencebtn.selected = NO;
    }
    self.AlltypeBtn.selected = NO;
    self.AllBusinessdistrictbtn.selected = NO;
    
    [self.noopsycheSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.noopsycheSingleTableView.dataArray =@[@"智能排序",@"距离排序"];
}

-(IBAction)AllBusinessdistrictbtn_action:(id)sender
{
    if(self.AllBusinessdistrictbtn.selected == NO)
    {
        self.AllBusinessdistrictbtn.selected = YES;
    }else
    {
        self.AllBusinessdistrictbtn.selected = NO;
    }
    self.Intelligencebtn.selected = NO;
    self.AlltypeBtn.selected = NO;
    [self.SelectCityTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.SelectCityTableView.dataArray =self.cityNameArray;
}

#pragma mark - singleTableViewDelegate
- (SingleTableView *)SelectCityTableView
{
    if (!_SelectCityTableView) {
        _SelectCityTableView = [[SingleTableView alloc] init];
        _SelectCityTableView.delegate = self;
        [self addChildViewController:_SelectCityTableView];
        [self.view addSubview:_SelectCityTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _SelectCityTableView.arrawImageView = self.addressImageView;
    }
    return _SelectCityTableView;
}

- (SingleTableView *)typeSingleTableView
{
    if (!_typeSingleTableView) {
        _typeSingleTableView = [[SingleTableView alloc] init];
        _typeSingleTableView.delegate = self;
        [self addChildViewController:_typeSingleTableView];
        [self.view addSubview:_typeSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _typeSingleTableView.arrawImageView = self.typeImageView;
    }
    return _typeSingleTableView;
}

- (void)singleTableView:(SingleTableView *)tableView didSelectedCellAtIndexPath:(NSIndexPath *)indexPath
{
    self.AlltypeBtn.selected = NO;
    self.AllBusinessdistrictbtn.selected = NO;
    self.Intelligencebtn.selected = NO;
    if (tableView == self.typeSingleTableView) {
        NSString *celltest =  @[@"全部分类",@"便利店",@"社区行政",@"社区医疗",@"生活服务",@"生鲜水果",@"餐饮旅社",@"便民维修",@"家政服务"][indexPath.row];
        if([celltest isEqualToString:@"全部分类"])
        {
            self.strOrder = @"";
        }else{
            self.navigationItem.title = celltest;
            self.strOrder = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        }
        if (celltest.length >= 5) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            ;
            [self.AlltypeBtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.AlltypeBtn setTitle:celltest forState:UIControlStateNormal];
        }
    }else if (tableView == self.SelectCityTableView)
    {
        NSString *celltest = self.cityNameArray[indexPath.row];
        self.strDistrict = [NSString stringWithFormat:@"%@",self.idArray[indexPath.row]];
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.AllBusinessdistrictbtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.AllBusinessdistrictbtn setTitle:celltest forState:UIControlStateNormal];
        }
    }
    else
    {
        NSString *celltest =@[@"智能排序",@"距离排序"][indexPath.row];
        self.strPrice = celltest;
        if([self.strPrice isEqualToString:@"智能排序"])
        {
            self.strPrice = @"";
        }
        if (celltest.length >= 5) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            ;
            [self.Intelligencebtn setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.Intelligencebtn setTitle:celltest forState:UIControlStateNormal];
        }
    }
    self.page = 1;
    [self webRequest_GetCityCommunityWithMore:NO];

}

- (SingleTableView *)noopsycheSingleTableView
{
    if (!_noopsycheSingleTableView) {
        _noopsycheSingleTableView = [[SingleTableView alloc] init];
        _noopsycheSingleTableView.delegate = self;
        [self addChildViewController:_noopsycheSingleTableView];
        [self.view addSubview:_noopsycheSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _noopsycheSingleTableView.arrawImageView = self.noopsycheImageView;
    }
    return _noopsycheSingleTableView;
}
#pragma mark - reset button size

//-(void)resetItemSizeBy:(NSString*)str{
//    if (str.length >= 5) {
//        NSString *btnTitle = [NSString stringWithFormat:@"%@..",[str substringWithRange:NSMakeRange(0, 4)]];
//        ;
//        [self.AllBusinessdistrictbtn setTitle:btnTitle forState:UIControlStateNormal];
//    }else{
//        [self.AllBusinessdistrictbtn setTitle:str forState:UIControlStateNormal];
//    }
//}


#pragma mark - FSDropDown datasource & delegate

//- (NSInteger)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
//    if (tableView == menu.rightTableView) {
//        return _cityArr.count;
//    }else{
//        return _currentAreaArr.count;
//    }
//}
//- (NSString *)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView titleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (tableView == menu.rightTableView) {
//        
//        return _cityArr[indexPath.row];
//    }else{
//        return _currentAreaArr[indexPath.row];
//    }
//}
//
//- (void)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if(tableView == menu.rightTableView){
//        _currentAreaArr = _areaArr[indexPath.row];
//        [menu.leftTableView reloadData];
//    }else{
//        self.isShowAddressList = NO;
//        self.AlltypeBtn.selected = NO;
//        self.AllBusinessdistrictbtn.selected = NO;
//        self.Intelligencebtn.selected = NO;
//        [self resetItemSizeBy:_currentAreaArr[indexPath.row]];
//    }
//}

-(void)cancleTabelView
{
    self.AlltypeBtn.selected = NO;
    self.AllBusinessdistrictbtn.selected = NO;
    self.Intelligencebtn.selected = NO;
}

-(void)senderCancle
{
    self.AlltypeBtn.selected = NO;
    self.AllBusinessdistrictbtn.selected = NO;
    self.Intelligencebtn.selected = NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
